package com.sofwin.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sofwin.pojo.SysUser;
import com.sofwin.pojo.SysUserExample;
import com.sofwin.system.mapper.SysUserMapper;
import com.sofwin.system.service.UserService;
import com.sofwin.vo.UserVO;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @packageName: com.sofwin.system.service.impl
 * @user: andyliu
 * @date: 2021/12/14 10:59
 * @email 115176513@qq.com
 * @description: TODO
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper mapper;
    @Override
    public SysUser checkLogin(SysUser user) {
        SysUserExample ex = new SysUserExample();
        SysUserExample.Criteria criteria = ex.createCriteria();
        if(user!=null){
            if(!StringUtils.isEmpty(user.getLoginAccount())){
                criteria.andLoginAccountEqualTo(user.getLoginAccount());
            }
            if(!StringUtils.isEmpty(user.getLoginPwd())){
                criteria.andLoginPwdEqualTo(user.getLoginPwd());
            }
        }

        List<SysUser> users = mapper.selectByExample(ex);
        if(users==null || users.size()==0){
            return null;
        }
        return users.get(0);
    }

    @Override
    public PageInfo<UserVO> selectByPage(SysUser user, Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber,pageSize);
        List<UserVO> users = mapper.selectUser(user);
        return  new PageInfo(users);
    }

    @Override
    public SysUser selectById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean saveOrUpdate(SysUser user) {
        if(!StringUtils.isEmpty(user.getLoginPwd())){
            String loginPwd = user.getLoginPwd();
            SimpleHash hash = new SimpleHash("MD5", loginPwd, user.getLoginAccount(), 1);
            user.setLoginPwd(hash.toString());
        }
        if(user.getId()!=null){
            return mapper.updateByPrimaryKeySelective(user)==1?true:false;
        }

        return mapper.insertSelective(user)==1?true:false;
    }

    @Override
    public boolean deleteById(Integer id) {
        return mapper.deleteByPrimaryKey(id)==1?true:false;
    }

    @Override
    public boolean deleteByIds(Integer[] ids) {
       int num = mapper.deleteByIds(ids);
        return num==ids.length?true:false;
    }
}
